<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - 后台管理系统</title>
    <link rel="stylesheet" href="../styles/styles-main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .login-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
            backdrop-filter: blur(10px);
        }

        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .login-header h1 {
            color: #333;
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 600;
        }

        .login-header p {
            color: #666;
            margin: 0;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.3s ease;
            box-sizing: border-box;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .login-button {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
        }

        .login-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .login-button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .error-message {
            background: #fee;
            border: 1px solid #fcc;
            color: #c33;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 14px;
            display: none;
        }

        .success-message {
            background: #efe;
            border: 1px solid #cfc;
            color: #3c3;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 14px;
            display: none;
        }

        .demo-accounts {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            font-size: 12px;
            color: #666;
        }

        .demo-accounts h4 {
            margin: 0 0 10px 0;
            color: #333;
        }

        .demo-account {
            margin: 5px 0;
            cursor: pointer;
            padding: 5px;
            border-radius: 5px;
            transition: background 0.3s ease;
        }

        .demo-account:hover {
            background: #e9ecef;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #ffffff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
            vertical-align: middle;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <h1><i class="fas fa-lock"></i> 后台管理系统</h1>
            <p>请输入您的账号信息登录系统</p>
        </div>

        <div id="errorMessage" class="error-message"></div>
        <div id="successMessage" class="success-message"></div>

        <form id="loginForm">
            <div class="form-group">
                <label for="email"><i class="fas fa-envelope"></i> 邮箱地址</label>
                <input type="email" id="email" name="email" required placeholder="请输入邮箱地址">
            </div>

            <div class="form-group">
                <label for="password"><i class="fas fa-key"></i> 密码</label>
                <input type="password" id="password" name="password" required placeholder="请输入密码">
            </div>

            <button type="submit" id="loginButton" class="login-button">
                <span id="loginText">登录系统</span>
                <span id="loginLoading" class="loading" style="display: none;"></span>
            </button>
        </form>

        <div class="demo-accounts">
            <h4><i class="fas fa-user-secret"></i> 测试账号</h4>
            <div class="demo-account" onclick="fillCredentials('admin@example.com', 'admin123')">
                <strong>管理员账号:</strong> admin@example.com / admin123
            </div>
            <div class="demo-account" onclick="fillCredentials('user@example.com', 'user123')">
                <strong>普通用户:</strong> user@example.com / user123
            </div>
        </div>
    </div>

    <script src="../common/api-client.js"></script>
    <script>
        const apiClient = new ApiClient({
            baseURL: 'http://localhost:3000',
            timeout: 10000
        });

        // 填充测试账号
        function fillCredentials(email, password) {
            document.getElementById('email').value = email;
            document.getElementById('password').value = password;
        }

        // 显示消息
        function showMessage(type, message) {
            const element = document.getElementById(type + 'Message');
            element.textContent = message;
            element.style.display = 'block';
            
            if (type === 'error') {
                document.getElementById('successMessage').style.display = 'none';
            } else {
                document.getElementById('errorMessage').style.display = 'none';
            }
        }

        // 隐藏消息
        function hideMessages() {
            document.getElementById('errorMessage').style.display = 'none';
            document.getElementById('successMessage').style.display = 'none';
        }

        // 处理登录
        async function handleLogin(event) {
            event.preventDefault();
            
            const email = document.getElementById('email').value.trim();
            const password = document.getElementById('password').value;
            const loginButton = document.getElementById('loginButton');
            const loginText = document.getElementById('loginText');
            const loginLoading = document.getElementById('loginLoading');

            // 验证输入
            if (!email || !password) {
                showMessage('error', '请输入邮箱和密码');
                return;
            }

            // 显示加载状态
            loginButton.disabled = true;
            loginText.textContent = '登录中...';
            loginLoading.style.display = 'inline-block';
            hideMessages();

            try {
                // 调用真实的后端API进行登录
                const response = await apiClient.post('/api/auth/login', {
                    email: email,
                    password: password
                });

                console.log('登录响应:', response);

                if (response.success) {
                    // 保存认证令牌
                    if (response.data && response.data.token) {
                        apiClient.setAuthToken(response.data.token);
                        
                        // 保存用户信息
                        localStorage.setItem('userInfo', JSON.stringify(response.data.user));
                        
                        showMessage('success', '登录成功！正在跳转...');
                        
                        // 延迟跳转，让用户看到成功消息
                        setTimeout(() => {
                            window.location.href = 'dashboard.html';
                        }, 1000);
                    } else {
                        showMessage('error', '登录响应数据格式错误');
                    }
                } else {
                    showMessage('error', response.message || '登录失败');
                }
            } catch (error) {
                console.error('登录错误:', error);
                
                // 添加详细的错误信息
                if (error.status === 401) {
                    showMessage('error', '邮箱或密码错误');
                } else if (error.status === 500) {
                    showMessage('error', '服务器内部错误，请稍后重试');
                } else if (error.message.includes('Network') || error.message.includes('Failed to fetch')) {
                    showMessage('error', '网络连接失败，请检查后端服务是否启动 (端口3000)');
                } else if (error.message.includes('timeout')) {
                    showMessage('error', '请求超时，后端服务可能未启动');
                } else {
                    showMessage('error', '登录失败: ' + error.message);
                }
            } finally {
                // 恢复按钮状态
                loginButton.disabled = false;
                loginText.textContent = '登录系统';
                loginLoading.style.display = 'none';
            }
        }

        // 检查是否已登录
        function checkLoginStatus() {
            const token = apiClient.getAuthToken();
            if (token) {
                // 如果已登录，直接跳转到仪表盘
                window.location.href = 'dashboard.html';
            }
        }

        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            checkLoginStatus();
            
            // 绑定表单提交事件
            document.getElementById('loginForm').addEventListener('submit', handleLogin);
            
            // 自动填充测试账号（开发环境）
            if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                fillCredentials('admin@example.com', 'admin123');
            }
        });

        // 回车键登录
        document.addEventListener('keypress', function(event) {
            if (event.key === 'Enter') {
                const activeElement = document.activeElement;
                if (activeElement.tagName === 'INPUT' && activeElement.type !== 'button') {
                    handleLogin(event);
                }
            }
        });
    </script>
</body>
</html>